/*
 * 文件名：ShoppingCarServiceImpl.java
 * 版权：
 * 描述：TODO
 * 修改人：zuo liubo
 * 修改时间：2013-2-4 下午7:46:48
 */
package com.scpii.api.service.ec.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.scpii.api.common.exception.ClientException;
import com.scpii.api.controller.ec.ShoppingCarController;
import com.scpii.api.domain.ec.Product;
import com.scpii.api.domain.ec.ShoppingCar;
import com.scpii.api.persistence.ec.ShoppingCarMapper;
import com.scpii.api.service.ec.ShoppingCarService;

/**
 * @description TODO
 * @author zuo liubo
 * @date 2013-2-4
 */
@Service("shoppingCarService")
public class ShoppingCarServiceImpl implements ShoppingCarService {

	private Log logger = LogFactory.getLog(ShoppingCarServiceImpl.class);
	@Resource
	private ShoppingCarMapper carMapper;
	private int affectRow ;
	@Override
	public Long insert(ShoppingCar car) {
		Long shoppingCarId = 0L;
		//查询该商品是否已加入购物车,根据用户ID，产品ID和备注来判断
		ShoppingCar _car = new ShoppingCar();
		_car.setUserId(car.getUserId());
		_car.setProduct(car.getProduct());
		String _note = car.getNote();
		if (_note != null && !_note.trim().equals("") ){
			_car.setNote(_note);
		}
		
		List<ShoppingCar> carList = carMapper.selectShoppingCarBySelective(_car);
		//未加入，则新增一条记录
		if(carList.size() > 0 ){
			//已经加入了，更新数量为原有的加上新增的
			_car = carList.get(0);
			_car.setQuantity(_car.getQuantity() + car.getQuantity());
			affectRow = carMapper.updateShoppingCarById(_car);
			if(affectRow != 1){
				throw new ClientException("insert shoppingcar error");
			}
			shoppingCarId = _car.getShoppingCarId();
		}else{
			shoppingCarId = carMapper.generateId();
			car.setShoppingCarId(shoppingCarId);
			affectRow = carMapper.insert(car);
			if(affectRow != 1){
				throw new ClientException("insert shoppingcar error");
			}
		}
		
		return shoppingCarId;
	}

	@Override
	public List<ShoppingCar> selectShoppingCarByUserId(ShoppingCar car) {
		return carMapper.selectShoppingCarBySelective(car);
	}

	@Override
	public Long updateShoppingCarById(ShoppingCar car) {
		affectRow = carMapper.updateShoppingCarById(car);
		if(affectRow == 0){
			throw new ClientException("update shoppingcar error");
		}
		return car.getShoppingCarId();
	}

	@Override
	public boolean deleteShoppingCar(List<Long> carIdList) {
		affectRow = carMapper.deleteShoppingCar(carIdList);
		return new Boolean(affectRow == 1);
	}

}
